<template>
  <div :class="[ns.b()]">
    <el-form ref="formRef" inline :model="searchConfig.fields">
      <el-space>
        <!-- input、select、date -->
        <!-- 第一个控件 -->
        <el-form-item v-for="item in searchConfig.control" :key="item.field" :prop="item.field">
          <component ref="controlRef" v-model:value="searchConfig.fields[item.field]" :is="controls[item.type]" :config="item" />
        </el-form-item>
        <!-- 第二个控件 -->
        <!-- <el-form-item>
          <el-input />
        </el-form-item> -->
        <!-- 按钮 -->
        <el-form-item>
          <el-space>
            <Button type="primary" @click="search">搜索</Button>
            <Button @click="reset">重置</Button>
          </el-space>
        </el-form-item>
      </el-space>
    </el-form>
  </div>
</template>
<script lang="ts">
  export default { name: 'SearchIndex' }
</script>
<script setup lang="ts">
  import { useUamespace } from '@/hooks/use-namesapce'

  import type { SearchInterface, EmitsInterface } from './types/props'
  // from
  import type { FormInstance } from 'element-plus'
  const props = withDefaults(defineProps<SearchInterface>(), {})
  const emit = defineEmits<EmitsInterface>()
  const ns = useUamespace('table-search-wrap')
  /**
   * ref
   */
  const formRef = ref<FormInstance>()
  const controlRef = ref(null)
  /**
   * 异步导入（按需加载，推荐）
   */
  const modules = import.meta.glob('./../**/index.vue', { eager: false })
  const controls = ref({})
  const loadModule = async () => {
    props.searchConfig.control.forEach(async (control) => {
      const type = control.type
      for (const key in modules) {
        if (key.indexOf(type) !== -1) {
          const module = await modules[key]()
          controls.value[type] = module.default
        }
      }
    })
  }
  loadModule()

  const search = () => {
    emit('search')
  }

  const reset = () => {
    // 重置控件数据
    controlRef.value.forEach((control) => control?.reset())
    formRef.value.resetFields()
    emit('reset')
  }
</script>
<style lang="scss" scoped>
  @include b(table-search-wrap) {
    :deep(.el-form-item) {
      margin-right: 0;
      margin-bottom: 0;
    }
  }
</style>
